package org.mbds.android.p2p.serviceinfos;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;

import org.mbds.android.p2p.services.P2pService;
import org.mbds.android.p2p.threads.ConnectToAPeer;
import org.mbds.android.p2p.threads.ServiceDiscovery;
import org.mbds.android.sismapp.activity.LoginActivity;

import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener;
import android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest;
import android.widget.Toast;

/**
 * 
 * @author doliere
 * This class holds information about the
 * SISMAPP service that will be registered for service discovery.
 * 3 fields : service_name, listening port and user_name.
 */
public class P2pServiceInfo{
	

	WifiP2pManager mManager;
	Channel mChannel;
	WifiP2pInfo mInfos;
	Map record;
	ServerSocket serverSocket;
	final HashMap<String, String> buddies = new HashMap<String, String>();
	DnsSdTxtRecordListener txtListener;
	DnsSdServiceResponseListener servListener;
	WifiP2pDnsSdServiceInfo serviceInfo;
	P2pService mService;
	boolean mDestroyService = false;
	
	public P2pServiceInfo(P2pService service, WifiP2pManager manager, Channel channel, ServerSocket server){
		mManager = manager;
		mChannel = channel;
		serverSocket = server;
		mService = service;
	}
	
	public void initServiceInfo(){
		initialize();
		initializeDiscovery();
		initializeDnsTxtRequest();
		initializeRequest();
	}
	
	public void initialize(){
		record = new HashMap();
        try {
			serverSocket = new ServerSocket(8888);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        record.put("PORT", String.valueOf(serverSocket.getLocalPort()));
        record.put("USER", LoginActivity.firstName + " " + LoginActivity.lastName);
        record.put("available", "visible");

        // Service information.  Pass it an instance name, service type
        // _protocol._transportlayer , and the map containing
        // information other devices will want once they connect to this one.
        serviceInfo =
                WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);

        // Add the local service, sending the service info, network channel,
        // and listener that will be used to indicate success or failure of
        // the request.
        mManager.addLocalService(mChannel, serviceInfo, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(mService.getApplicationContext(), "Service added", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int arg0) {
                Toast.makeText(mService.getApplicationContext(), "Adding service failed", Toast.LENGTH_SHORT).show();
                mService.setLocalServiceRegistrationFailed(true);
            }
        });
        
	    
	 
	}
	
	public void initializeRequest(){
		   WifiP2pDnsSdServiceRequest serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
	        mManager.addServiceRequest(mChannel,
	                serviceRequest,
	                new WifiP2pManager.ActionListener() {
	                    @Override
	                    public void onSuccess() {
	    	                Toast.makeText(mService.getApplicationContext(), "ADD REQUEST SUCCESSFUL", Toast.LENGTH_SHORT).show();
	                    }

	                    @Override
	                    public void onFailure(int code) {
	    	                Toast.makeText(mService.getApplicationContext(), "ADD REQUEST FAILED", Toast.LENGTH_SHORT).show();
	    	                mService.addRequestFailed();
	                    }
	                });
	}
	
	public void initializeDnsTxtRequest(){
		txtListener = new DnsSdTxtRecordListener() {
		       
	        /* Callback includes:
	         * fullDomain: full domain name: e.g "printer._ipp._tcp.local."
	         * record: TXT record dta as a map of key/value pairs.
	         * device: The device running the advertised service.
	         */

			@Override
			public void onDnsSdTxtRecordAvailable(String fullDomainName,
					Map<String, String> record, WifiP2pDevice device) {
                Toast.makeText(mService.getApplicationContext(), "DNS TXT" + device.deviceName, Toast.LENGTH_SHORT).show();
              
			}
	    };
	    
	     servListener = new DnsSdServiceResponseListener() {
	        @Override
	        public void onDnsSdServiceAvailable(String instanceName, String registrationType,
	                WifiP2pDevice device) {
                Toast.makeText(mService.getApplicationContext(), "DNS SERVICE", Toast.LENGTH_SHORT).show();
                mService.addDnsDevice(device);
                //Add this device in the list of devices.
	        }
	    };

	    mManager.setDnsSdResponseListeners(mChannel, servListener, txtListener);
	    
	}
	public void initializeDiscovery(){
		 mManager.discoverServices(mChannel, new WifiP2pManager.ActionListener() {

	            @Override
	            public void onSuccess() {
	                Toast.makeText(mService.getApplicationContext(), "DISCOVERY SUCCESSFUL", Toast.LENGTH_SHORT).show();
	            }

	            @Override
	            public void onFailure(int code) {
	                Toast.makeText(mService.getApplicationContext(), "DISCOVERY FAILED", Toast.LENGTH_SHORT).show();
	                new ServiceDiscovery(mService).execute();
	            }
	        });
	}
	
	public WifiP2pDnsSdServiceInfo getServiceInfo(){
		return serviceInfo;
	}
}
